#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/10/29 22:25
# @Author  : Nabby
# @File    : user_impl.py.py
# @Desc    :

from app import db
import uuid
from infrastructure.po.mode.dict_type import DictType
from infrastructure.po.mode.dict_data import DictData
from sqlalchemy import and_, or_, desc, asc

class DictTypeImpl(object):
    @classmethod
    def get_dict_type_list(cls, name=None, page=1, page_size=999):
        """
        查询字典类型列表
        :param name: 查询
        :param page: 页码
        :param page_size: 每页数量
        :return:
        """
        query = db.session.query(DictType)
        if name is not None:
            query = query.filter(
                DictType.name.like('%' + name + '%')
            )
        return query.paginate(page=page, per_page=page_size).items, query.count()


    @classmethod
    def add_dict_type(cls, name, remark=None):
        count = db.session.query(DictType).filter(
            DictType.name == name
        ).count()
        if count == 0:
            dict_type = DictType(
                id=str(uuid.uuid4()),
                name=name,
                remark=remark
            )
            db.session.add(dict_type)
            db.session.flush()
            db.session.commit()
            return True
        else:
            return False

    @classmethod
    def update_dict_type(cls, dict_type_id, name):
        count_name = db.session.query(DictType).filter(
            DictType.id != dict_type_id,
            DictType.name == name
        ).count()
        if count_name == 0:
            DictType.query.filter(DictType.id == dict_type_id).update(
                {DictType.name: name}
            )
            db.session.commit()
            return True
        else:
            return False

    @classmethod
    def delete_dict_type(cls, dict_type_id):
        """
        删除字典类型
        :param dict_id: 字典类型id
        :return:
        """
        # 判断字典类型是否有关联字典，有则无法删除
        count = db.session.query(DictData).filter(
            DictData.dict_type_id == dict_type_id
        ).count()
        if count > 0:
            return False
        # 删除字典类型
        DictType.query.filter(DictType.id == dict_type_id).delete()
        db.session.commit()
        return True





